<template>

  <div class="setting-items">
    <div class="profile-form-shell">
      <p>基本信息</p>
      <el-form
          ref="formData"
          :model="profileForm"
          class="profile-form"
          label-position="right"
          label-width="auto"
          :rules="rules"
      >
        <el-form-item label="用户名" prop="nickName">
          <el-input v-model="profileForm.nickName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="profileForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker v-model="profileForm.birth"></el-date-picker>
        </el-form-item>
        <el-form-item label="个人介绍">
          <el-input v-model="profileForm.personDescription"
                    type="textarea"
                    placeholder="个人介绍将在您的主页展示"></el-input>
        </el-form-item>
        <el-form-item label="兴趣标签">
          <p v-if="!checkedTags.length" class="tags-title">请从下列标签中进行选择</p>
          <div class="hobby-tag">
            <div class="checked-tag">
              <el-tag
                  class="checked-tag-item"
                  v-for="tag in checkedTags"
                  :key="tag.name"
                  closable
                  @close="closeTag(tag.name)"
              >
                {{ tag.name }}
              </el-tag>
            </div>
            <div class="tags">
              <el-check-tag
                  class="tag-item"
                  type="info"
                  :checked="tag.checked"
                  v-for="(tag,index) in tags" :key="index"
                  @change="checkedTag(tag.name)"
              >
                {{ tag.name }}
              </el-check-tag>
            </div>
          </div>
        </el-form-item>
        <el-form-item label=" ">
          <el-button type="primary" @click="onSubmit($refs.loader,$refs.formData,$event)">保存修改</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="icon-uploader">
      <el-upload
          class="uploader"
          ref="loader"
          :action="policy.host"
          :data="policy"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleChoose"
      >
        <div class="mask">修改头像</div>
        <el-avatar :size="100" :src="imgUrl || profileForm.iconUrl">
          <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
        </el-avatar>
      </el-upload>
      <div class="title">
        <span v-if="!imgUrl">上传头像</span>
        <button v-if="imgUrl" class="cancel-upload-btn" @click="cancelIconChoose">撤销上传</button>
      </div>
      <p v-if="!imgUrl" class="description">
        格式：支持JPG、PNG、JEPG <br>
        5M以内
      </p>
      <p v-if="imgUrl" class="description">点击下方保存修改后生效</p>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {getOssPolicyApi} from '@/api/fileUploadApi.js'
import {useUserStore} from "@/store/userStore.js";
import {setProfileApi} from "@/api/userApi.js";


const userStore = useUserStore();

/**
 * 表单数据
 */
let profileForm = ref({})
onMounted(() => {
  profileForm.value = userStore.userInfo
})


/**
 * 本地选择图片的url
 */
let imgUrl = ref('')

/**
 * 选择本地图片后的回调
 */
async function handleChoose(e) {
  console.log(e)
  if (e.status !== 'ready') return // 判断选择的文件状态，防止重复触发事件
  if (e.raw.type !== 'image/jpeg') {
    ElMessage.error('头像仅支持JPG格式!')
    return false
  } else if (e.raw.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过2MB!')
    return false
  }
  // createObjectURL，接受一个 Blob 实例作为参数，返回一个 URL 对象
  imgUrl.value = URL.createObjectURL(e.raw);
}

/**
 * 取消选择头像
 */
function cancelIconChoose() {
  imgUrl.value = ''
}

/**
 * 兴趣标签
 */
let tags = ref(
    [
      {name: 'vue', checked: false},
      {name: 'java', checked: false},
      {name: 'javascript', checked: false},
      {name: '大数据', checked: false},
      {name: '软件测试', checked: false},
      {name: '算法', checked: false},
      {name: '人工智能', checked: false},
      {name: '机器学习', checked: false},
    ]
)
/**
 * 选择的标签
 */
let checkedTags = ref([])

/**
 * 选择标签的回调
 * @param name
 */
function checkedTag(name) {
  // 修改标签状态
  tags.value.forEach(tag => {
    if (tag.name === name) tag.checked = !tag.checked
  })
  // 过滤出被选中的标签
  checkedTags.value = tags.value.filter(tag => tag.checked)
}

/**
 * 取消选择标签的回调
 * @param name
 */
function closeTag(name) {
  checkedTag(name)
}

/**
 * 提交表单
 * @param loader el-loader事件对象
 * @param formData form 对象
 * @param e
 */
async function onSubmit(loader, formData, e) {
  await formData.validate()  //表单校验
  if (imgUrl.value !== '' && imgUrl.value !== null) {
    await handleUpload(loader)  //上传图片到阿里云oss
  }
  console.log(profileForm.value)
  let response = await setProfileApi(profileForm.value);
  userStore.userInfo = response.data
  profileForm.value = response.data
  //清空表单数据
  imgUrl.value = ''
  //刷新图片,当img标签的url发生变化时，浏览器会强制刷新图片
  profileForm.value.iconUrl = profileForm.value.iconUrl + '?' + Date.now()
  ElMessage.success('修改成功')
}

/**
 * 阿里云oss签名对象
 */
let policy = ref({
  OSSAccessKeyId: '',
  policy: '',
  signature: '',
  dir: '',
  key: '',
  host: '',
  success_action_status: '200',
  expire: '' // 签名过期时间
})
/**
 * 上传图片
 */
const handleUpload = async (uploader) => {

  //获取oss签名
  let response = await getOssPolicyApi(0, 'userPhoto.jpg');
  policy.value = response.data
  await uploader.submit() // 手动上传
  profileForm.value.iconUrl = policy.value.host + '/' + policy.value.key //拼接上传后的图片url
  return true
}

/**
 * 表单校验规则
 */
const rules = ({
  nickName: [
    {required: true, message: '用户名不能为空', trigger: 'blur'},
    {min: 3, max: 10, message: "用户名长度为3-10个字符", trigger: "blur"}
  ],
  sex: [
    {required: true, message: '性别不能为空', trigger: 'blur'}
  ],
})
</script>

<style lang="scss" scoped>
@import "@/styles/var";
.setting-items {
  display: flex;
  justify-content: space-between;

  :deep(.el-form) {
    .el-form-item {
      margin-bottom: 2rem;
    }
  }

  .profile-form-shell {
    width: 60%;
    padding: 1rem;

    .profile-form {
      margin: 1rem 0;

      .tags-title {
        color: $color-placeholder-text;
      }

      .hobby-tag {
        .checked-tag {
          .checked-tag-item {
            margin-right: 0.5rem;
          }
        }

        .tags {
          position: relative;
          top: 0.5rem;
          padding: 0.5rem 0.5rem 0;
          border: 1px solid $color-border-light;
          border-radius: 5px;

          .tag-item {
            margin: 0 0.5rem 0.5rem 0;
            cursor: pointer;
            font-size: 0.8rem;
            font-weight: normal;
          }

          .tag-item:hover {
            background-color: $color-light-0;
          }
        }
      }
    }
  }

  .icon-uploader {
    width: 40%;
    padding: 1rem;

    .uploader {
      display: flex;
      justify-content: center;

      :deep(.el-upload) {
        position: relative;

        .mask {
          width: 100px;
          height: 100px;
          position: absolute;
          border-radius: 50%;
          opacity: 0;
          text-align: center;
          line-height: 100px;
          font-size: 0.8rem;
          color: $color-white;
        }

        :hover.mask {
          opacity: 1;
          background-color: rgba(0, 0, 0, 0.5);
        }

        img {
          width: 100px;
          height: 100px;
          object-fit: cover;
          border-radius: 50%;

        }
      }
    }

    .title {
      margin: 0.5rem 0;

      .cancel-upload-btn {
        color: $color-theme;
        background-color: transparent;
      }
    }

    .title, .description {
      text-align: center;
      color: $color-placeholder-text;
      font-size: 0.8rem;
    }

  }
}
</style>